#!/usr/bin/python
#coding=utf-8

"""基本工具类。

包括导入对象、渲染模板、分页、md5、检查图片格式等
常规操作。
"""

from jinja2 import Environment, FileSystemLoader
import hashlib
from datetime import datetime
import uuid

def import_obj(fullname):
    parts = fullname.split('.')
    pkg, classname = '.'.join(parts[:-1]), parts[-1]
    cls = __import__(pkg, None, None, classname, 0)
    return getattr(cls, classname)()

def render(template_name, args=None):
    env = Environment(
            loader = FileSystemLoader("templates"),
            auto_reload = True
    )   
    env.autoescape = True
    template = env.get_template(template_name)
    if args:
        page = template.render(args).encode('utf8')
    else:
        page = template.render().encode('utf8')
    return page

def singleton(cls, *args, **kw):  
    instances = {}  
    def _singleton():  
        if cls not in instances:  
            instances[cls] = cls(*args, **kw)  
        return instances[cls]  
    return _singleton  

def md5(passwd, salt='netease'):
    return hashlib.md5(passwd.lower()+salt).hexdigest()   

def gen_sign(*data):
    """生成md5签名。
    规则为：输入参数拼接然后md5加密。
    """
    data = list(data)
    data.sort()
    sign_str = reduce(lambda x, y: '%s%s' % (x, y), data)
    sign = hashlib.md5(sign_str).hexdigest()
    return sign

def gen_bid():
    """生成充值的bid,长度为32个字符。
    规则为：当前时间(20字符) + 12位随机字符
    """
    str_now = str(datetime.now())
    str_filter = filter(lambda x: x!='-' and x!=':' and x!='.' and x!=' ', 
        str_now)
    random = uuid.uuid1().get_hex()[0:12]
    bid = '%s%s' % (str_filter, random)
    return bid
